﻿<!DOCTYPE html>
<html>
<head>
    <title>Twitter Client</title>
    <script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="../js/knockout-2.1.0.min.js"></script>
    <script type="text/javascript" src="../js/twitterApi.js"></script>
    <link rel="stylesheet" type="text/css" href="../css/reset.css" />
    <link rel="stylesheet" type="text/css" href="../css/style.css" />
</head>
<body>
    <h1>Retrieve the tweets!</h1>
    <p>Please provide your search term</p>
    <div>
        <form data-bind="submit: getTweets">
        <label>
            Search:</label>
        <input data-bind="value: twitterName" />
        <span id="loading" class="loading" data-bind="visible: loading">
            <img src="../images/loading.gif" alt="loading" />
            Loading...
        </span>
        </form>
    </div>
    <div class="buttonholder">
        <button data-bind="click: getTweets">
            <img src="../images/metro.icons/white/refresh.png" /></button>
        <img src="../images/metro.icons/white/heart.png" onclick="document.location.href='/'" />
    </div>
    <div data-bind="with: resultData">
        <h3>Recent tweets fetched at 
        <span data-bind="text: retrievalDate"></span>
        </h3>
        <ul data-bind="foreach: topTweets">
            <li data-bind="html: (replaceURLWithHTMLLinks(text))"></li>
        </ul>
        <button data-bind="click: $parent.clearResults">
            <img src="../images/metro.icons/white/delete.png" />
        </button>
    </div>
    <script type="text/javascript">
        function AppViewModel() {

            var self = this;
            self.loading = ko.observable(false);
            self.twitterName = ko.observable('@comdaybe');
            self.resultData = ko.observable();
            self.getTweets = function () {

                //start loading animation
                self.loading(true);

                //retrieve tweets by using twitterApi
                twitterApi.getTweetsForUser(self.twitterName(), function (data) {
                    self.resultData({
                        retrievalDate: new Date(),
                        topTweets: data.slice(0, 5)
                    });

                    //stop loading animation
                    self.loading(false);
                });
            }

            self.clearResults = function () {
                self.resultData(undefined);
            }
        }

        ko.applyBindings(new AppViewModel());

        function replaceURLWithHTMLLinks(text) {
            var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
            return text.replace(exp, "<a href='$1'>$1</a>");
        }
    </script>
</body></html>